谈谈 mobx
是什么
MobX 通过响应式编程实现简单高效,可扩展的状态管理。
API
@observable
Observable 值可以是 JS 基本数据类型、引用类型、普通对象、类实例、数组和映射。其修饰的 state 会暴露出来供观察者使用@action
只有在 actions 中,才可以修改 Mobx 中 state 的值@computed
计算值是可以根据现有的状态或其它计算值衍生出的值observer
: 监控 Component 组件的状态变化 可以用作包裹 React 组件的高阶组件。 在组件的 render 函数中的任何已使用的 observable 发生变化时,组件都会自动重新渲染。 注意 observer 是由 "mobx-react" 包提供的,而不是 mobx 本身
Mobx 概念
- Action:修改 State(同 Vuex 中 Mutations)
- State
- Computed Values(同 Vuex 中 Getter)
- Reactions
怎么用
import React from "react";
import { makeAutoObservable } from "mobx";
import { observer } from "mobx-react-lite";
// store
class AppState {
constructor() {
// 监听器
makeAutoObservable(this);
}
// state
timer = 0;
// action
add = () => {
this.timer += 1;
};
sub = () => {
this.timer -= 1;
};
}
// 子组件
const TimerView = observer(({ appState }) => {
return (
<div>
{appState.timer}
<div>
<button onClick={appState.add}>+1</button>
<button onClick={appState.sub}>-1</button>
</div>
</div>
);
});
// 父组件
function App() {
const appState = new AppState();
return (
<div>
<TimerView appState={appState} />
</div>
);
}
export default App;